import pymysql

from com.utils.DbHelper import DbHelper


class UserController():

    def regist(self,username,password):
        # 校验用户名和密码不能为空
        if username ==None or password ==None or username.strip()=="" or password.strip()=="":
            return {"status":400,"msg":"用户名密码不能为空"}
        else:
            #校验用户名不存在
            dbHelper = DbHelper("test")
            sql1 = "select * from user where username =%s"
            user = dbHelper.queryOne(sql1,(username,))
            if user is None:
                sql = "insert into user(username,password) values(%s,%s)" # 参数化 使用%s进行占位
                n =dbHelper.update(sql,(username,password)) # 执行sql的时候将要进行替换的值 封装为一个元组传参执行
                if n >0:
                    return {"status":200,"msg":"注册成功"}
                else:
                    return {"status": 500, "msg": "注册异常"}
            else:
                return {"status": 300, "msg": "该用户名已被占用"}


    def login(self,username,password):
        # 创建dbhelper对象
        dbHelper = DbHelper("test")
        # 查询用户名是否存在
        sql1 = "select * from user where username = %s"
        user = dbHelper.queryOne(sql1,(username,))
        if user is None:
            return {"status": 400, "msg": "用户不存在"}
        else:
            # 创建sql语句
            sql2 = "select * from user where username = %s and password = %s"
            # 执行sql
            result = dbHelper.queryOne(sql2,(username,password))
            # 判断查询是否存在
            if(result is not None):
                return {"status":200,"msg":"登录成功"}
            else:
                return {"status":500,"msg":"密码错误"}